<template>
  <div>
    <div style="text-align: center; margin-bottom: 20px; margin-top: 40px">
      <el-date-picker
        v-model="selectedMonth"
        type="month"
        placeholder="选择月份"
        format="YYYY年MM月"
        value-format="YYYY-MM"
      />
      <el-button type="primary" @click="load" style="margin-left: 10px">
        搜索
      </el-button>
    </div>
    <div id="echarts-dom" style="width: 100%; height: 1200px"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import request from "@/utils/request";

require("echarts/theme/macarons");

export default {
  name: "calendar-pie-chart",
  data() {
    return {
      data: [],
      selectedMonth: this.getCurrentMonthRange()[0],
      option: {
        tooltip: {
          trigger: "item",
          formatter: " 分数: {c}",
        },
        legend: {
          data: [
            { name: "优秀 (>90)", itemStyle: { color: "#6BCB77" } },
            { name: "良好 (80-90)", itemStyle: { color: "#FFD93D" } },
            { name: "需改进 (<80)", itemStyle: { color: "#FF6B6B" } },
          ],
          bottom: 20,
        },
        calendar: {
          top: "100px",
          left: "center",
          orient: "vertical",
          cellSize: [120, 120],
          yearLabel: {
            show: false,
            fontSize: 30,
          },
          dayLabel: {
            margin: 40,
            firstDay: 1,
            nameMap: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
            fontSize: 25,
            color: "#333",
          },
          monthLabel: {
            show: false,
          },
          range: this.getCurrentMonthRange(),
        },
        series: [
          {
            id: "label",
            type: "scatter",
            coordinateSystem: "calendar",
            symbolSize: 0,
            label: {
              show: true,
              formatter: (params) => {
                return echarts.time.format(params.value[0], "{dd}", false);
              },
              offset: [-40, -40],
              fontSize: 14,
            },
          },
        ],
      },
      myEcharts: null,
      chartData: [],
      today: this.getTodayDateString(),
    };
  },
  created() {
    this.load();
  },
  mounted() {
    this.createEcharts();
  },
  methods: {
    handleMonthChange() {
      this.load();
    },

    async load() {
      this.data[0] = `${this.selectedMonth}-01`;
      this.data[1] = `${this.selectedMonth}-31`;
      try {
        const res = await request.get("/check/finden", {
          params: {
            date1: this.data[0],
            date2: this.data[1],
          },
        });
        if (res.code === "0") {
          console.log(this.data);
          console.log(res.data.records);

          console.log(this.data[0]);
          console.log(this.selectedMonth);
          this.processApiData(res.data.records);
        }
      } catch (error) {
        console.error("获取评分数据失败:", error);
      }
    },
    processApiData(apiData) {
      const [year, month] = this.selectedMonth.split("-").map(Number);
      const daysInMonth = new Date(year, month, 0).getDate();

      this.chartData = [];
      for (let day = 1; day <= daysInMonth; day++) {
        const dayStr = `${year}-${month < 10 ? "0" + month : month}-${
          day < 10 ? "0" + day : day
        }`;
        const apiItem = apiData.find((item) => item.date === dayStr);
        this.chartData.push([dayStr, apiItem ? apiItem.grade : null]);
      }

      this.option.calendar.range = [this.selectedMonth];
      this.updateChartSeries();
    },
    getTodayDateString() {
      const date = new Date();
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${year}-${month < 10 ? "0" + month : month}-${
        day < 10 ? "0" + day : day
      }`;
    },
    getCurrentMonthRange() {
      const date = new Date();
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      return [`${year}-${month < 10 ? "0" + month : month}`];
    },
    createEcharts() {
      const chartDom = document.getElementById("echarts-dom");
      this.myEcharts = echarts.init(chartDom, "macarons");
      this.myEcharts.setOption(this.option, true);
      window.addEventListener("resize", this.handleResize);
      this.myEcharts.on("click", (params) => {
        if (params.seriesType === "pie") {
          this.highlightToday();
        }
      });
    },
    updateChartSeries() {
      const pieSeries = this.chartData.map((item, index) => {
        const isToday = item[0] === this.today;
        const score = item[1];
        const isUnrated = score === null || score === undefined || score === "";

        let color;
        if (isUnrated) {
          color = "#CCCCCC";
        } else if (score < 80) {
          color = "#FF6B6B";
        } else if (score >= 80 && score <= 90) {
          color = "#FFD93D";
        } else {
          color = "#6BCB77";
        }

        return {
          type: "pie",
          id: "pie-" + index,
          center: item[0],
          radius: 30,
          coordinateSystem: "calendar",
          label: {
            formatter: isUnrated ? "无" : score.toString(),
            position: "center",
            fontSize: 14,
            fontWeight: "bold",
            color: "#333",
          },
          itemStyle: {
            color: isToday ? "#409EFF" : color,
          },
          data: [
            {
              name: isUnrated ? "未评分" : "卫生评分",
              value: isUnrated ? 1 : score,
              itemStyle: {
                color: isToday ? "#409EFF" : color,
              },
            },
          ],
          tooltip: {
            formatter: (params) => {
              let content = `<div style="font-weight:bold">日期：${item[0]}</div>`;
              if (isUnrated) {
                content += `<div>状态：未评分</div>`;
              } else {
                let level = "";
                if (score < 80) level = "（需改进）";
                else if (score >= 80 && score <= 90) level = "（良好）";
                else level = "（优秀）";
                content += `<div>卫生评分：${score}${level}</div>`;
              }
              return content;
            },
          },
        };
      });

      this.option.legend.data = [
        { name: "优秀 (>90)", itemStyle: { color: "#6BCB77" } },
        { name: "良好 (80-90)", itemStyle: { color: "#FFD93D" } },
        { name: "需改进 (<80)", itemStyle: { color: "#FF6B6B" } },
        { name: "未评分", itemStyle: { color: "#CCCCCC" } },
        { name: "今日", itemStyle: { color: "#409EFF" } },
      ];

      this.option.series = [
        {
          ...this.option.series[0],
          data: this.chartData,
        },
        ...pieSeries,
      ];

      if (this.myEcharts) {
        this.myEcharts.setOption(this.option, true);
      }
    },
    highlightToday() {
      const todayIndex = this.chartData.findIndex(
        (item) => item[0] === this.today
      );
      if (todayIndex >= 0) {
        this.myEcharts.dispatchAction({
          type: "highlight",
          seriesIndex: 1 + todayIndex,
          dataIndex: 0,
        });
      }
    },
    handleResize() {
      if (this.myEcharts) {
        this.myEcharts.resize();
      }
    },
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
    if (this.myEcharts) {
      this.myEcharts.off("click");
      this.myEcharts.dispose();
    }
  },
};
</script>